package com.shopping.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.shopping.pojo.vo.LoginInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {
    // 设置过期时间
    private static final long EXPIRE_DATE = 30 * 60 * 1000;
    private static final String TOKEN_SECRET = "Shopping";
    public static Boolean result = false;
    public static String message = "";

    public static String token(String userName, String identity,Integer userId) {
        String token = "";
        try {
            // 过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            // 秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            // 携带username、email信息,生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("userName", userName)
                    .withClaim("userId", userId)
                    .withClaim("identity",identity)
                    .withExpiresAt(date)
                    .sign(algorithm);

        } catch (Exception e) {
            return null;
        }
        return token;
    }

    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            result = true;
            return result;
        } catch (TokenExpiredException e) {
            result = false;
            message = "登录状态过期,请重新登录";
            return result;
        } catch (Exception e) {
            result = false;
            message = "token不正确";
            return result;
        }
    }

    public static LoginInfo getUserByToken(String token) {
        DecodedJWT decodedJWT = JWT.decode(token);
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUserName(decodedJWT.getClaim("userName").asString());
        loginInfo.setUserId(decodedJWT.getClaim("userId").asInt());
        loginInfo.setIdentity(decodedJWT.getClaim("identity").asString());
        return loginInfo;
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }
        return token;
    }
}
